/*
 * Copyright @ 2025 weili23
 * com.example.ai 9:45
 * All right reserved.
 */

package com.example.ai;

import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.Resource;
import javax.lang.model.element.VariableElement;
import java.io.IOException;

/**
 * @desc: 高亮查询
 * @author: weili23
 * @createTime: 2025/8/18 9:45
 * @version: v1.0
 */
@SpringBootTest
public class HighlightSearch {
    @Resource
    private RestHighLevelClient client;

    private static final String INDEX_NAME = "person";
    @Test
    void search() throws IOException {
        SearchRequest searchRequest = new SearchRequest(INDEX_NAME);
        SearchSourceBuilder builder = new SearchSourceBuilder();
        //设置查询条件
        builder.query(QueryBuilders.matchQuery("description", "曹操"));
        //设置高亮信息
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("description",  100);
        highlightBuilder.field("name", 100);
        highlightBuilder.preTags("<font style='color:red'>");
        highlightBuilder.postTags("</font>");

        builder.highlighter(highlightBuilder);

        searchRequest.source(builder);
        SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
        SearchHit[] hits = search.getHits().getHits();
        for (SearchHit hit : hits){
            System.out.println(hit.getSourceAsString());
            System.out.println(hit.getHighlightFields());
        }
    }
}
